#include "NetAddr.hpp"
#include <arpa/inet.h>
#include <cstdio>
#include <cstdlib>


namespace tcplib
{

    void NetAddr::clear()
    {
        bzero(&_addr, sizeof(_addr)); 
        _addr.sin_family = AF_INET; 
    }

    NetAddr::NetAddr()
    {
        clear();
    }


    NetAddr::NetAddr(const struct sockaddr_in &addr)
    {
        _addr = addr;
    }

    NetAddr::NetAddr(const char *ip_port)
    {
        char ip[24];
        const char *sport = NULL;
        for(int i = 0; ip_port[i] != '\0'; i++) {
            if (ip_port[i] == ':') {
                sport = &ip_port[i+1];
                break;
            }

            ip[i] = ip_port[i];
            ip[i+1] = '\0';
        }

        uint16_t port = 80;
        if (sport)
            port = atoi(sport);
        set_ip_port(ip, port);
    }

    NetAddr::NetAddr(uint16_t port)
    {
        set_ip_port("0.0.0.0", port);
    }


    NetAddr::NetAddr(const char *ip, uint16_t port)
    {
        set_ip_port(ip, port);
    }

    void NetAddr::set_ip_port(const char *ip, uint16_t port)
    {
        clear();
        ::inet_pton(AF_INET, ip, &_addr.sin_addr);
        _addr.sin_port = htons(port);
    }


    std::string NetAddr::to_ip_port()
    {
        char ip[24];
        char ip_port[32];
        ::inet_ntop(AF_INET, &_addr.sin_addr, ip, 24);
        snprintf(ip_port, 32, "%s:%d", ip, ntohs(_addr.sin_port));
        return ip_port;
    }

};


